package com.ty.xiaoyu.service.impl;

import com.ty.xiaoyu.entity.Great;
import com.ty.xiaoyu.entity.Topic;
import com.ty.xiaoyu.exception.GreatOperationException;
import com.ty.xiaoyu.service.GreatService;
import com.ty.xiaoyu.util.MyTimeUtil;
import com.ty.xiaoyu.util.RandomIdUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GreatServiceImpl extends BaseService implements GreatService {

    @Override
    public Great getGreatByTopicIdAndUserId(String topicId, String userId) {
        return greatMapper.queryGreatByTopicIdAndUserId(topicId, userId);
    }

    @Override
    public void cancelGreat(Great great) throws GreatOperationException {
        great.setLastUpdateTime(MyTimeUtil.nowTime());
        great.setGreatState(0);
        Integer state = greatMapper.deleteGreat(great);
        if (state <= 0) {
            throw new GreatOperationException("取消点赞失败");
        }
    }

    @Override
    public void editGreat(Great great) throws GreatOperationException {
        great.setLastUpdateTime(MyTimeUtil.nowTime());
        great.setGreatState(1);
        Integer state = greatMapper.updateGreat(great);
        if (state <= 0) {
            throw new GreatOperationException("点赞失败");
        }
    }

    @Override
    public void addGreat(Great great) throws GreatOperationException {
        great.setGreatId(RandomIdUtil.getId());
        great.setCreatTime(MyTimeUtil.nowTime());
        great.setLastUpdateTime(MyTimeUtil.nowTime());
        great.setGreatState(1);
        Integer state = greatMapper.insertGreat(great);
        if (state <= 0) {
            throw new GreatOperationException("点赞失败");
        }
    }

    @Override
    public List<Great> getGreatListByUserId(String userId) throws GreatOperationException {
        List<Great> greatList = greatMapper.queryGreatListByUserId(userId);
        if (greatList == null || greatList.isEmpty()) {
            throw new GreatOperationException("未找到点在记录");
        }
        for (Great great : greatList) {
            Topic topic = topicMapper.queryTopicById(great.getTopicId());
            great.setTopic(topic);
        }
        return greatList;
    }
}
